
export const toString = Object.prototype.toString;

/**判断是否为纯对象, 指的是通过字面量形式或者new Object()形式定义的对象*/
export function isPlainObject(val: any): boolean {
    if (toString.call(val) !== '[object Object]') {
        return false;
    }

    var prototype = Object.getPrototypeOf(val);
    return prototype === null || prototype === Object.prototype;
}

/**
 * bind方法兼容写法
 * @param fn 
 * @param thisArg 
 */
export function bind(fn: Function, thisArg: any) {
    return function wrap(...args: any) {
        return fn.apply(thisArg, args);
    };
}

/**
 * a 继承 b
 * @param a 继承对象
 * @param b 被继承对象
 * @param thisArg this上下文
 */
export function extend(a: any, b: any, thisArg?: any): any {
    forEach(b, function assignValue(val, key) {
        if (thisArg && typeof val === 'function') {
            a[key] = bind(val, thisArg);
        } else {
            a[key] = val;
        }
    });
    return a;
}

/**兼容数组和对象的forEach */
export function forEach(obj: any, fn: (val: any, key?: string, obj?: any) => void) {
    // Don't bother if no value provided
    if (obj === null || typeof obj === 'undefined') {
        return;
    }

    // Force an array if not already something iterable
    if (typeof obj !== 'object') {
        /*eslint no-param-reassign:0*/
        obj = [obj];
    }

    if (isArray(obj)) {
        // Iterate over array values
        for (var i = 0, l = obj.length; i < l; i++) {
            fn.call(null, obj[i], i, obj);
        }
    } else {
        // Iterate over object keys
        for (var key in obj) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) {
                fn.call(null, obj[key], key, obj);
            }
        }
    }
}

/**判断是否为数组 */
export function isArray(val) {
    return toString.call(val) === '[object Array]';
}